<template>
  <div class="header">
    <img src="@/assets/images/left.png" @click="goBack" />
    <div class="header-input">
      <i class="iconfont icon-fangdajing"></i>
      <input
        type="text"
        v-model="keyword"
        v-focus
        placeholder="搜您喜欢的产品..."
        @keyup.enter="search"
      />
      <img
        v-show="keyword"
        src="@/assets/images/del.png"
        alt=""
        @click="keyword = ''"
      />
    </div>
    <div class="header-icon" @click="search">
      <span>搜索</span>
    </div>
  </div>
</template>

<script>
export default {
  name: "Header",
  data() {
    return {
      keyword: "",
      searchHistory: [],
    };
  },
  methods: {
    goBack() {
      this.keyword = "";
      this.$router.go(-1);
    },
    search() {
      if (!this.keyword) return;

      //存储 搜索历史
      if (!localStorage.getItem("searchHistory")) {
        localStorage.setItem("searchHistory", "[]");
      } else {
        this.searchHistory = JSON.parse(localStorage.getItem("searchHistory"));
      }
      this.searchHistory.unshift(this.keyword);
      //需要去重
      localStorage.setItem(
        "searchHistory",
        JSON.stringify([...new Set(this.searchHistory)])
      );

      this.$router.push({
        name: "searchList",
        query: { key: this.keyword },
      });
    },
  },
  mounted() {
    this.$bus.$on("setKeyword", (val) => {
      this.keyword = val;
    });
  },
};
</script>

<style lang='scss' scoped>
.header {
  background-color: #95111c;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: sticky;
  left: 0;
  top: 0;
  height: 1.3333rem;
  width: 100%;
  z-index: 999;

  img {
    width: 1.0667rem;
  }
  &-input {
    border: 0.0267rem solid #fff;
    background-color: #fff;
    width: 90%;
    height: 0.8rem;
    border-radius: 0.4533rem;
    padding: 0 0.2133rem;
    color: rgb(179, 171, 171);
    display: flex;
    align-items: center;
    margin: 0 0.1333rem;

    i {
      font-size: 0.48rem;
      padding-right: 0.1333rem;
    }

    input {
      width: 100%;
      height: 0.8rem;
      border-radius: 0.4533rem;
      outline: none;
      border: none;
      padding-right: 0.2667rem;
    }
    img {
      width: 0.48rem;
    }
  }
  &-icon {
    span {
      display: inline-block;
      width: 1.2rem;
      height: 1.3333rem;
      line-height: 1.3333rem;
      font-size: 0.4267rem;
      color: #fff;
    }
  }
}
</style>